/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sni.org.pe.utilitario;

import java.util.HashMap;
import javax.naming.InitialContext;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.NamingException;
import sni.org.pe.handler.ExceptionHandler;

/**
 *
 * @author ehuamani
 */
public class ServiceLocator {

   private Logger LOG = Logger.getLogger(ServiceLocator.class.getName());
   HashMap serviceCache = null;
   InitialContext context = null;
   private static ServiceLocator serviceLocator = null;
   private Hashtable<String, Object> caching = new Hashtable<String, Object>(5);
   private static final String JNDI_BASE_ENTRY = "java:comp/env/ejb/";

   public ServiceLocator() {
      try {
         serviceCache = new HashMap();
         context = new InitialContext();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static ServiceLocator getInstance() throws NamingException {
      if (serviceLocator == null) {
         serviceLocator = new ServiceLocator();
      }
      return serviceLocator;
   }

   public Object findService(String name) {
      try {
         Object objRef;
         if (null == (objRef = caching.get(name))) {
            InitialContext ic = new InitialContext();
            objRef = ic.lookup(JNDI_BASE_ENTRY + name);
            caching.put(name, objRef);
         }
         return objRef;
      } catch (NamingException e) {
         LOG.severe(e.getMessage());
      }
      return null;
   }

   public Object findServiceRemote(String name) {
      Object objRef = null;
      try {
         final Context context = getInitialContext();
         objRef = context.lookup("sni.org.pe.session.remote." + name + "SessionEJBRemote");
      } catch (Exception ex) {
         ex.printStackTrace();
      }
      return objRef;
   }
   
       private Context getInitialContext() throws NamingException, ExceptionHandler {
        Hashtable env = new Hashtable();
        // Estableciendo el contexto inicial para GlassFish
        //env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.appserv.naming.S1ASCtxFactory");
        env.put(Context.PROVIDER_URL, "iiop://localhost:3700");
        return new InitialContext(env);
    }
}
